/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package se.superduperbudget.superbudgetuser;

import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.WebResource;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.datatype.DatatypeConfigurationException;
import javax.xml.datatype.DatatypeConstants;
import javax.xml.datatype.DatatypeFactory;
import javax.xml.datatype.XMLGregorianCalendar;
import se.superduperbudget.superbudgetuser.TransactionList.Transaction;
import se.superduperbudget.superbudgetuser.banks.Banks;
import se.superduperbudget.superbudgetuser.user.User;

/**
 *
 * @author olofbjerke
 */
public class BudgetServlet extends HttpServlet {

    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    private static final String CONTENT_TYPE = "text/html";
    private String targetServlet = "http://home.emilan.se:8084/rs/user/";
    
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        //response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {
            String action;
            if((action = request.getParameter("action")) != null) {
            
                
                
                if(action.equals("getLatestTransactions")) {
                    
                    
                    HttpSession session = request.getSession();
                    User user = (User) session.getAttribute("user");
                    
                    String params = "recenttransactions/1";
                            
                    

                    URL url = new URL( targetServlet + "recenttransactions/" + user.getUuid());
                    //JAXBContext jc = JAXBContext.newInstance(TransactionList.class);
                    //Unmarshaller u = jc.createUnmarshaller();
                    //TransactionList tl = (TransactionList) u.unmarshal(url);
                    BufferedReader in = new BufferedReader(
                    new InputStreamReader(
                    url.openStream()));

                      String inputLine;

                      while ((inputLine = in.readLine()) != null)
                         out.println(inputLine);

                      in.close();


                }
                
                
                else if(action.equals("getBanks")) {
                    
                    
                    HttpSession session = request.getSession();
                    User user = (User) session.getAttribute("user");
                    
                    String params = "recenttransactions/1";
                            
                    

                    URL url = new URL( "http://home.emilan.se:8084/rs/admin/bank" );
                    //JAXBContext jc = JAXBContext.newInstance(TransactionList.class);
                    //Unmarshaller u = jc.createUnmarshaller();
                    //TransactionList tl = (TransactionList) u.unmarshal(url);
                    BufferedReader in = new BufferedReader(
                    new InputStreamReader(
                    url.openStream()));

                      String inputLine;

                      while ((inputLine = in.readLine()) != null)
                         out.println(inputLine);

                      in.close();
                    
                }
                
                
                else if(action.equals("saveUser")) {
                    HttpSession session = request.getSession();
                    User user = (User )session.getAttribute("user");
                    
                    String p = null;
                    if((p = request.getParameter("fName")) != null)
                        user.setFName(p);
                    if((p = request.getParameter("lName")) != null)
                        user.setLName(p);
                    if((p = request.getParameter("email")) != null)
                        user.setEmail(p);
                    if((p = request.getParameter("password")) != null)
                    {
                        String q = null;
                        if((q = request.getParameter("password2")) != null && p.equals(q))
                            user.setPassword(p);
                        
                    }
                    
                    StringWriter sw  = new StringWriter();

                    JAXBContext jc = JAXBContext.newInstance(User.class);
                    Marshaller m = jc.createMarshaller();
                    m.marshal(user, sw);
                    System.out.println(sw);

                    Client client = Client.create();
                    WebResource web = client.resource("http://home.emilan.se:8084/rs/admin/user");

                    web.type("application/xml").put(sw.toString());

                    //response.sendRedirect("index.xhtml");

                    out.println("true");

                }
                
                
                
                else if(action.equals("addTransaction")) {
                    float diff          = 0;
                    String      title = request.getParameter("title");
                    String      bank = "egna";
                    String      date = request.getParameter("date");
                    if(request.getParameter("diff") != null && !request.getParameter("diff").equals(""))
                        diff = Float.parseFloat(request.getParameter("diff"));
                    String[]    tags = request.getParameterValues("tags[]");
                    
                    
                    /*
                    JAXBElement<TransactionList> jaxbe = generateXML(
                            title,
                            bank,
                            date,
                            tags);
                    
                    
                    String data = out(jaxbe);
                    System.out.println(data);
                    boolean res = postXML(data);
                    */
                    
                    TransactionList tl = new TransactionList();
                    Transaction t = new Transaction();
                    t.setTitle(title);
                    t.setDate(generateDate(date));
                    t.setDiff(diff);
                    List<Transaction> list = tl.getTransaction();
                    list.add(t);
                    
                    
                    StringWriter sw  = new StringWriter();

                    JAXBContext jc = JAXBContext.newInstance(TransactionList.class);
                    Marshaller m = jc.createMarshaller();
                    m.marshal(t, sw);
                    System.out.println(sw);

                    //Client client = Client.create();
                    //WebResource web = client.resource("http://home.emilan.se:8084/rs/admin/user");

                    //web.type("application/xml").put(sw.toString());
                    
                    
                    
                    
                    
                    out.println(true);
   
                }
                
                
                
                
                
                else if(action.equals("getSettings")) {
                    HttpSession session = request.getSession();
                    User user = (User) session.getAttribute("user");
                    
                    JAXBContext jc = JAXBContext.newInstance(User.class);
                    Marshaller m = jc.createMarshaller();
                    m.marshal(user, out);

                    
                }
            
            
            
            
            
            }
        } catch (JAXBException ex) {
            Logger.getLogger(BudgetServlet.class.getName()).log(Level.SEVERE, null, ex);
        } finally {            
            out.close();
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
    
 /*   
    private JAXBElement<TransactionList> generateXML(
            String title,
            String bank,
            String sDate,
            String[] tags) {
        
        XMLGregorianCalendar    date = generateDate(sDate);   
        TagList                 taglist = new TagList();
        ArrayList<Tag>          tg = (ArrayList<Tag>) taglist.getTag();
        Tag                     t;
        int                     n = 0;
        
        if(tags != null) {
            while(n < tags.length) {
                t = new Tag();
                t.setName(tags[n++]);
                tg.add(t);
            }
        }    

        
        
        
        // Skapa en transaction
        UserTransaction ut = new UserTransaction();
        ut.setTitle(title);
        ut.setBank(bank);
        if(date != null)
            ut.setDate(date);
        ut.setTaglist(taglist);

        // Skapa en transactionlist
        TransactionList txl = new TransactionList();
        ArrayList<UserTransaction> txs = (ArrayList<UserTransaction>) txl.getTransaction();
        txs.add(ut);

        // Skapa JAXBElementet....
        ObjectFactory of = new ObjectFactory();
        JAXBElement<TransactionList> list = of.createTransactionList(txl);

        return null;
    }
  */  
    
    /*
     * Genererar en string från ett jaxbelement som innehåller vår xml data.
     */
    private String out(JAXBElement<TransactionList> xml) {
        
        Marshaller m;
        java.io.StringWriter sw = new StringWriter();
        
        try {
            
            JAXBContext context = JAXBContext.newInstance(TransactionList.class);

            m = context.createMarshaller();
            m.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
            m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

            m.marshal(xml, sw);
            
        } catch (JAXBException ex) {
            System.out.println("nope :/");
            System.out.println(ex);
            Logger.getLogger(BudgetServlet.class.getName()).log(Level.SEVERE, null, ex);
        }
     
        return sw.toString();
        
    }
    
    
    /*
     * Postar xml till valfri servlet
     * 
     */
    private boolean postXML(String xml) {
        try {
            OutputStreamWriter outputWriter = null;
            InputStreamReader inputReader   = null;
            BufferedReader br               = null;
            String line                     = null;
            URL url                         = null;
            HttpURLConnection connection    = null;
            StringBuilder sb                = new StringBuilder();
            
                sb.append(xml);
                url = new URL(targetServlet + "?action=addTransaction" );
                
                if(url != null)
                    connection = (HttpURLConnection)url.openConnection();
                connection.setDoOutput(true);
                connection.setRequestMethod("POST");
                connection.setRequestProperty("Content-Length", "" + sb.length());
                outputWriter = new OutputStreamWriter(connection.getOutputStream());
                outputWriter.write(sb.toString());
                outputWriter.flush();
                outputWriter.close();
                
                inputReader = new InputStreamReader(connection.getInputStream());
                br = new BufferedReader(inputReader);
                
                if((line = br.readLine()) != null && line.equals("true"))
                    return true;
                else return
                        false;
                
        } catch (IOException ex) {
            System.out.println(ex);
            Logger.getLogger(BudgetServlet.class.getName()).log(Level.SEVERE, null, ex);
            return false;
        }
    }
    
    
    // Generates from this form : 2004-05-30T09:00:00
    // 2011-02-03T10:10:10+00:01
    private XMLGregorianCalendar generateDate(String sDate) {
        
        Date dateObject = new Date();
        SimpleDateFormat simpleDateformat= new SimpleDateFormat("yyyy");
        int year = Integer.parseInt(simpleDateformat.format(dateObject));
        
        simpleDateformat= new SimpleDateFormat("MM");
        int month = Integer.parseInt(simpleDateformat.format(dateObject));
        
        
        
        XMLGregorianCalendar date = null;
        
        try {
            date = DatatypeFactory.newInstance().newXMLGregorianCalendar();

            date.setYear(year);
            date.setMonth(month);
            date.setDay(3);
            date.setHour(5);
            date.setMinute(10);
            date.setSecond(0);

        } catch (DatatypeConfigurationException ex) {
            Logger.getLogger(BudgetServlet.class.getName()).log(Level.SEVERE, null, ex);
        }
        
    
        return date;
    }
}
